import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import babel from "vite-plugin-babel";
// import topLevelAwait from 'vite-plugin-top-level-await'
import path from 'path'

// https://vitejs.dev/config/

const resolve = pathUrl => {
  return path.join(__dirname, pathUrl)
}

export default defineConfig((({ command, mode, ssrBuild }) => {
  const env = loadEnv(mode, process.cwd(), '');
  const result = {
    base: './',
    // plugins
    plugins: [
      react(),
      babel({
        extensions: ['.js', '.jsx', '.es6', '.es', '.mjs', '.vue'],
        babelHelpers: 'runtime',
        test: /.m?js$/,
        include: [
          path.resolve("node_modules/pdfjs-dist/"),
        ],
        presets: [
          [
            '@babel/preset-env',
            {
              modules: "commonjs"
            }
          ]
        ],
        plugins: [
          [
            '@babel/plugin-transform-runtime',
            {
              corejs: false,
              helpers: true,
              regenerator: true,
              useESModules: false
            }
          ]
        ]
      }),
      // topLevelAwait({
      //   // The export name of top-level await promise for each chunk module
      //   promiseExportName: '__tla',
      //   // The function to generate import names of top-level await promise in each chunk module
      //   promiseImportName: i => `__tla_${i}`
      // })
    ],
    esbuild: {
      pure: [],
    },
    build: {
      outDir: "dist",
      minify: "esbuild",
      rollupOptions: {
        output: {
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
        },
      },
      target: "es2019",
    },
    resolve: {
      alias: {
        // "@": resolve(__dirname, "./src"),
        '@src': resolve('src'),
        "@assets": resolve('src/assets'),
        "@service": resolve('src/service'),
        "@common": resolve('src/common'),
        "@components": resolve('src/components'),
        "@pages": resolve('src/pages'),
        "@styles": resolve('src/styles'),
        "@api": resolve('src/api'),
        // store: resolve('src/store'),
        "@utils": resolve('src/utils')
      },
    },

  }
  if (command === 'serve') {
    return {
      // dev 独有配置
      ...result,
      build: { sourcemap: false },
      css: {
        preprocessorOptions: {
          less: {
            javascriptEnabled: true,
            // additionalData: `@import "@/styles/var.less";`,
            // modifyVars: {
            //   "@primary-color": "#4377FE", //设置antd主题色
            // },
          },
        },
      },
      server: {
        host: "0.0.0.0", // 服务器主机名，如果允许外部访问，可设置为"0.0.0.0"
        port: 7000,
        // open: viteEnv.VITE_OPEN,
        cors: true,
        // 代理跨域地址配置（官网几种写法）
        proxy: {
          '/mine': {
            target: 'https://edu-platform-file.oss-cn-hangzhou.aliyuncs.com',
            // target: 'https://bj-obs-java.obs.cn-east-3.myhuaweicloud.com',
            ws: false,        			  //如果要代理 websockets，配置这个参数
            secure: false,  			  // 如果是https接口，需要配置这个参数
            changeOrigin: true,  		  //是否跨域
            rewrite: (path) => path.replace(/^\/mine/, '/'),
          },
          '/yj-admin': {
            // target: 'http://115.29.204.54/',
            target: 'http://2n7z018744.vicp.fun/',
            ws: true,        			  //如果要代理 websockets，配置这个参数
            secure: false,  			  // 如果是https接口，需要配置这个参数
            changeOrigin: true,  		  //是否跨域
          }
        },
      },
    }
  } else {
    // command === 'build'
    return {
      ...result,
      build: {
        sourcemap: false,
        minify: "terser", // 必须开启：使用terserOptions才有效果
        terserOptions: {
          compress: {
            keep_infinity: true,  // 防止 Infinity 被压缩成 1/0，这可能会导致 Chrome 上的性能问题
            drop_console: false,   // 生产环境去除 console
            drop_debugger: true   // 生产环境去除 debugger
          },
        },
        // ...result
        // build 独有配置
      }
    }
  }
  }))


